//
//  AssetsOrderListViewController.m
//  DBAChain
//
//  Created by Evan on 2018/9/24.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "AssetsOrderListViewController.h"
#import <Masonry.h>
#import "taskJiaoYiService.h"
#import "OrderQiuGouTableViewCell.h"
#import "taskOverviewService.h"
#import "JiaoYiDetailViewController.h"
#import "AssetsOrderOverTableViewCell.h"
#import "JiaoYiPageDetailViewController.h"
#import "CommonData.h"

@interface AssetsOrderListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UISegmentedControl* segmCheck;
@property (nonatomic,strong)    UITableView *tableView;

@property (nonatomic,strong)     NSArray<dataOrderBuyAndSaleInfo *> *    orderList;
@property (nonatomic,strong)     NSArray<dataOrderDetailsInfo *> *    orderDetailsList;

@end

@implementation AssetsOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订单";
    
    [self segmCheck];
//    [self tableView];
    
    [self loadDataQiuGou:0];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    if (self.navigationController.navigationBar.hidden == YES) {
        self.navigationController.navigationBar.hidden = NO;
    }
    self.hidesBottomBarWhenPushed = YES;
    if (self.tabBarController.tabBar.hidden == NO) {
        self.tabBarController.tabBar.hidden = YES;
    }
    [self setBlackStatus:YES];
    [self segmentValueChanged:self.segmCheck];
    [self.tableView reloadData];
}

-(void)goBack:(id)sender{
    [self goRootBack:2];
}

#pragma mark - loadData

///订单申诉交易及已完成列表
///0 交易中 1 已完成 2 申诉中
-(void)loadDataSJ:(NSInteger)intSJ{
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:@(0) value:@"page"];
    [dict setField:@"50" value:@"pageSize"];
    [dict setField:@(intSJ) value:@"orderType"];//交易类型：0 交易中 1 已完成 2 申诉中
    [dict setValue:[UserCenter shareCenter].user.userNo forKey:@"userNo"];
    [taskOverviewService getOrderDetails:dict success:^(dataOrderDetails *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            self.orderDetailsList = response.orderList;
            [self.tableView reloadData];
            return ;
        }
        [DKProgressHUD showErrorWithStatus:response.statusDesc];
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

///获取求购和出售列表
///0:求购   1:出售
-(void)loadDataQiuGou:(NSInteger)intQiuGou{
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:@(0) value:@"page"];
    [dict setField:@"10" value:@"pageSize"];
    [dict setField:@(intQiuGou) value:@"orderType"];//交易类型：0 求购 1 出售
    [dict setValue:[UserCenter shareCenter].user.userNo forKey:@"userNo"];
    [taskOverviewService getOrderBuyAndSaleList:dict success:^(dataOrderBuyAndSale *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            self.orderList = response.orderList;
            [self.tableView reloadData];
            return ;
        }
        [DKProgressHUD showErrorWithStatus:response.statusDesc];
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}


#pragma mark - UISegmentedControl

-(UISegmentedControl*)segmCheck{
    if (!_segmCheck) {
        _segmCheck = [[UISegmentedControl alloc]initWithItems:@[@"求购中",@"出售中",@"交易中",@"已完成",@"申诉中"]];
        [self.view addSubview:_segmCheck];
        [_segmCheck mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view);
            make.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.view.mas_top).offset(64);
            make.height.offset(40);
        }];
        _segmCheck.tintColor = [UIColor clearColor];
        NSDictionary *selected = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:LCFromRGB(240, 92, 164)};
        //定义未选中状态下的样式normal，类型为字典
        NSDictionary *normal = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:LCFromRGB(51, 51, 51)};
        [_segmCheck setTitleTextAttributes:normal forState:UIControlStateNormal];
        [_segmCheck setTitleTextAttributes:selected forState:UIControlStateSelected];
        
        _segmCheck.selectedSegmentIndex = 0;
        [_segmCheck addTarget:self action:@selector(segmentValueChanged:)forControlEvents:UIControlEventValueChanged];
    }
    return _segmCheck;
}

///标题点击
-(void)segmentValueChanged:(UISegmentedControl*)sender{
    if ([self isQiuGou]) {
        [self loadDataQiuGou:sender.selectedSegmentIndex];
        return;
    }else if([self isSJ]){
        [self loadDataSJ:sender.selectedSegmentIndex - 2];
        return;
    }
}



#pragma mark - tableivew
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
            make.top.mas_equalTo(self.segmCheck.mas_bottom).offset(0);
        }];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        //定义显示默认cell的横线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate

//定义每一个section有多少row
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

//定义有多少section
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([self isQiuGou]) {
        return [self.orderList count];
    }else if([self isSJ]){
        return [self.orderDetailsList count];
    }
    return 0;
}

//定义CellRow的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segmCheck.selectedSegmentIndex == 0 || self.segmCheck.selectedSegmentIndex == 1) {
        return 74;
    }else if([self isSJ]){
        return 119.5;
    }
    return 0;
}

//定义section的Footer的view视图
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.backgroundColor = COLOR_Background;
    return view;
}

//定义section的Footer的高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

//定义section的header的view视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [UIView new];
//    if (section == 0) {
//        view.backgroundColor = [UIColor whiteColor];
//
//    }else{
        view.backgroundColor = COLOR_Background;
//    }
    return view;
}

//定义section的header的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

//主体cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self isQiuGou]) {
        OrderQiuGouTableViewCell *cell = [OrderQiuGouTableViewCell cellWithTableView:tableView IndexPath:indexPath];
        dataOrderBuyAndSaleInfo *m =  [self.orderList objectAtIndex:indexPath.section];
        dataOrderBuyAndSaleInfo *mm = [dataOrderBuyAndSaleInfo mj_objectWithKeyValues:m];
        cell.labelCNY.text = [NSString stringWithFormat:@"%@ CNY",mm.rmbAmount];
        cell.labelGTE.text = [NSString stringWithFormat:@"%@ GTE",mm.gteCoin];
        cell.labelTime.text = mm.orderTime;
        cell.labelPrice.text = [NSString stringWithFormat:@"单价：%@CNY  限额：%@CNY",mm.price,mm.limitAmount];
        
        return cell;
    }else if([self isSJ]){
        AssetsOrderOverTableViewCell *cell = [AssetsOrderOverTableViewCell cellWithTableView:tableView IndexPath:indexPath];
        
        dataOrderDetailsInfo *m = [self.orderDetailsList objectAtIndex:indexPath.section];
        dataOrderDetailsInfo *mm = [dataOrderDetailsInfo mj_objectWithKeyValues:m];
        
//        NSInteger segmIndex = self.segmCheck.selectedSegmentIndex - 2;
//        if (segmIndex == 0) {//交易中
            cell.labelDate.text = mm.createTime;
            cell.labelName.text = mm.nickName;
            cell.labelAmount.text =  mm.descStr;
            cell.labelOrderNo.text = [NSString stringWithFormat:@"交易额：%@",mm.orderAmount];
            [cell.imgHeader sd_setImageWithURL:[NSURL URLWithString:mm.imageUrl] placeholderImage:[UIImage imageNamed:@"icon_avatar"]];
            NSString *strType = mm.status == 0 ?@"买入GTE":@"卖出GTE";
            cell.labelType.text = strType;
//        }
        NSString *strStatus = [CommonData getOrderStatus:mm.orderType];
        cell.labelStatus.text = strStatus;
        
        return cell;
        
        
    }
    return  [UITableViewCell new];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self isQiuGou]) {
        
        [[UIAlertController alloc] alertTitle:@"取消订单" alertMessage:@"确定要取消该订单么？" leftCancelTitle:@"放弃" leftCancel:nil rightTitle:@"立即取消" rightOK:^(UIAlertAction *action) {
            
            dataOrderBuyAndSaleInfo *m =  [self.orderList objectAtIndex:indexPath.row];
            dataOrderBuyAndSaleInfo *mm = [dataOrderBuyAndSaleInfo mj_objectWithKeyValues:m];
            [DKProgressHUD showLoading];
            NSMutableDictionary *dict=  [NSMutableDictionary new];
            [dict setValue:mm.orderNo forKey:@"orderNo"];
            [dict setValue:@(self.segmCheck.selectedSegmentIndex) forKey:@"orderType"];
            [taskOverviewService getCancelOrder:dict success:^(BaseModel *response, BOOL success) {
                [DKProgressHUD dismiss];
                if (success) {
                    [DKProgressHUD showSuccessWithStatus:@"取消订单成功"];
                    [self loadDataQiuGou:self.segmCheck.selectedSegmentIndex];
                }else{
                    [DKProgressHUD showErrorWithStatus:response.statusDesc];
                }
                
            } failture:^(NSError *error, NSString *strDescription) {
                [DKProgressHUD dismiss];
                [DKProgressHUD showErrorWithStatus:strDescription];
            }];
        }];
        
    }else if([self isSJ]){
        ///交易中  选项卡
        if (self.segmCheck.selectedSegmentIndex == 2 || self.segmCheck.selectedSegmentIndex == 3) {
            JiaoYiPageDetailViewController *vc = [JiaoYiPageDetailViewController new];
            dataOrderDetailsInfo *m = [self.orderDetailsList objectAtIndex:indexPath.section];
            dataOrderDetailsInfo *mm = [dataOrderDetailsInfo mj_objectWithKeyValues:m];
//            NSInteger segmIndex = self.segmCheck.selectedSegmentIndex - 2;
            vc.isQiuGou = mm.status == 0;
            vc.modelOrderDetailsInfo = mm;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}


#pragma mark - 优化函数

///当前segm 是否是购买页
- (BOOL)isQiuGou{
    if (self.segmCheck.selectedSegmentIndex == 0 || self.segmCheck.selectedSegmentIndex == 1) {
        return YES;
    }
    return NO;
}

///当前segm 是否是交易页--已完成--申诉
- (BOOL)isSJ{
    if (self.segmCheck.selectedSegmentIndex == 2 || self.segmCheck.selectedSegmentIndex == 3|| self.segmCheck.selectedSegmentIndex == 4) {
        return YES;
    }
    return NO;
}

@end
